package com.mapaoer.user.controller;

import com.mapaoer.user.dto.EnterpriseProfileDTO;
import com.mapaoer.user.entity.User;
import com.mapaoer.user.service.EnterpriseProfileService;
import com.mapaoer.user.service.UserService;
import com.mapaoer.user.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 企业资料控制器
 * 处理企业资料相关的API请求
 */
@RestController
@RequestMapping("/api/enterprise")
public class EnterpriseProfileController {

    @Autowired
    private EnterpriseProfileService enterpriseProfileService;

    @Autowired
    private UserService userService;

    /**
     * 创建企业资料
     * @param enterpriseProfileDTO 企业资料
     * @return 创建结果
     */
    @PostMapping("/profile")
    @PreAuthorize("hasRole('ENTERPRISE')")
    public ResponseEntity<ResponseResult<?>> createEnterpriseProfile(@Valid @RequestBody EnterpriseProfileDTO enterpriseProfileDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        enterpriseProfileDTO.setUserId(user.getId());
        boolean result = enterpriseProfileService.createEnterpriseProfile(enterpriseProfileDTO);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("企业资料创建成功"));
        } else {
            return ResponseEntity.badRequest().body(ResponseResult.error("企业资料已存在"));
        }
    }

    /**
     * 更新企业资料
     * @param enterpriseProfileDTO 企业资料
     * @return 更新结果
     */
    @PutMapping("/profile")
    @PreAuthorize("hasRole('ENTERPRISE')")
    public ResponseEntity<ResponseResult<?>> updateEnterpriseProfile(@Valid @RequestBody EnterpriseProfileDTO enterpriseProfileDTO) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        EnterpriseProfileDTO existingProfile = enterpriseProfileService.getEnterpriseProfileByUserId(user.getId());
        if (existingProfile == null) {
            return ResponseEntity.notFound().build();
        }
        
        boolean result = enterpriseProfileService.updateEnterpriseProfile(existingProfile.getId(), enterpriseProfileDTO);
        if (result) {
            return ResponseEntity.ok(ResponseResult.success("企业资料更新成功"));
        } else {
            return ResponseEntity.badRequest().body(ResponseResult.error("企业资料更新失败"));
        }
    }

    /**
     * 获取当前登录企业的资料
     * @return 企业资料
     */
    @GetMapping("/profile")
    @PreAuthorize("hasRole('ENTERPRISE')")
    public ResponseEntity<ResponseResult<?>> getCurrentEnterpriseProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        User user = userService.getUserByUsername(username);
        
        EnterpriseProfileDTO profile = enterpriseProfileService.getEnterpriseProfileByUserId(user.getId());
        if (profile != null) {
            return ResponseEntity.ok(ResponseResult.success(profile));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 获取指定ID的企业资料
     * @param id 企业资料ID
     * @return 企业资料
     */
    @GetMapping("/profile/{id}")
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ENTERPRISE', 'ADMIN')")
    public ResponseEntity<ResponseResult<?>> getEnterpriseProfileById(@PathVariable Long id) {
        EnterpriseProfileDTO profile = enterpriseProfileService.getEnterpriseProfileById(id);
        if (profile != null) {
            return ResponseEntity.ok(ResponseResult.success(profile));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 根据公司名称搜索企业
     * @param companyName 公司名称关键词
     * @return 企业列表
     */
    @GetMapping("/search/name")
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ENTERPRISE', 'ADMIN')")
    public ResponseEntity<ResponseResult<?>> searchEnterprisesByName(@RequestParam String companyName) {
        List<EnterpriseProfileDTO> enterprises = enterpriseProfileService.searchEnterprisesByName(companyName);
        return ResponseEntity.ok(ResponseResult.success(enterprises));
    }

    /**
     * 根据行业搜索企业
     * @param industry 行业
     * @return 企业列表
     */
    @GetMapping("/search/industry")
    @PreAuthorize("hasAnyRole('DEVELOPER', 'ENTERPRISE', 'ADMIN')")
    public ResponseEntity<ResponseResult<?>> searchEnterprisesByIndustry(@RequestParam String industry) {
        List<EnterpriseProfileDTO> enterprises = enterpriseProfileService.searchEnterprisesByIndustry(industry);
        return ResponseEntity.ok(ResponseResult.success(enterprises));
    }
}